package com.self.console.service;

import com.self.console.proxy.ProxyHttpClient;
import com.self.console.proxy.RequestResult;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 抓取和讯黄金行情
 */
@Service
public class CrawlQuotationHexunService {
	protected static final Pattern pattern = Pattern.compile("^(-?[0-9])*[.]?([0-9])+$");
	
	public String crawlQuotation() {
		String goldPrice = "";
		try {
			RequestResult result = ProxyHttpClient.httpRequest("http://gold.hexun.com/hjxh/", "UTF-8");
			String html = result.getContent();
			Document doc = Jsoup.parse(html);
			Elements elements = doc.getElementsByTag("table");
			Element element = elements.get(5);
			Element tr = element.getElementsByTag("tr").get(5);
			goldPrice = tr.getElementsByTag("td").get(3).text().trim();
			goldPrice = isFloat(goldPrice);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return goldPrice;
	}
	
	/**
	 * 判断行情是否能转换成Float类型
	 */
	protected final static String isFloat(String f) {
		f = f.trim();
		Matcher matcher = pattern.matcher(f);
		if (!matcher.find()) {
			f = "0";
		}		
		return f;
	}

	public static void main(String[] args) {
		CrawlQuotationHexunService service = new CrawlQuotationHexunService();
		service.crawlQuotation();
	}
}
